package com.ljy.jymail.product.exeception;

import com.ljy.common.exception.BizCodeEnum;
import com.ljy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/*
* 集中处理异常
* 系统错误码：
* 10：通用
* 11：商品
* 12：订单
* 13：购物车
* 14:物流
* 001：格式校验
*
*
* */

@Slf4j
@RestControllerAdvice(basePackages = "com.ljy.jymail.product.app")
public class JyMailExeceptionControllerAdvice {



    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> re = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            re.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",re);
    }


    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){
        System.out.println(e);

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }

}
